package com.dony.common.utils.file;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BadPdfFormatException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author sundw
 * @version 1.0.0
 * @description PdfUtils
 * @since 2023/11/10 10:44
 */
public class PdfUtils {

    public static byte[] mergeMultiplePdfs(List<byte[]> pdfBytesList) throws IOException {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            Document document = new Document();
            PdfCopy copy = new PdfCopy(document, outputStream);
            document.open();

            for (byte[] pdfBytes : pdfBytesList) {
                addPdfToCopy(copy, pdfBytes);
            }

            document.close();
            return outputStream.toByteArray();
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }

    private static void addPdfToCopy(PdfCopy copy, byte[] pdfBytes) throws IOException {
        PdfReader reader = null;
        try {
            reader = new PdfReader(pdfBytes);
            int numberOfPages = reader.getNumberOfPages();
            for (int pageNum = 1; pageNum <= numberOfPages; pageNum++) {
                copy.addPage(copy.getImportedPage(reader, pageNum));
            }
        } catch (BadPdfFormatException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }
}
